var express = require('express');
var router = express.Router();
var userModel = require('../database/model/clientModel');

//加密密码
var bcrypt = require('bcryptjs')
var salt = bcrypt.genSaltSync(10); //加密盐

//token验证
var jwt = require('jsonwebtoken')
var secret = 'thisiszhangliisprivatekeypleasedonotpassiton' //私钥

/* 登录 */
router.get('/', function (req, res, next) {
  let { name, password } = req.query;
  userModel.find({ name: name }).then(result => {
    if (!result.length) {
      res.send({
        code: 0,
        msg: '登录失败，用户名不存在！'
      })
      return;
    };
    let bool = bcrypt.compareSync(password, result[0].password);
    if (!bool) {
      res.send({
        code: 0,
        msg: '密码错误,请重试'
      })
      return
    }
    let userInfo = result[0]
    userInfo.password = ''
    jwt.sign({  //签发token
      time: Date.now(), //签发时间
      limit: 10*1000  //有效时长
    },
      secret, //私钥，未来可以用于解析token
      (err, token) => {
        res.send({
          code: 666,
          msg: '登录成功',
          data: {
            userInfo,
            token
          }
        })
      })
  })
});

// 注册
router.post('/', function (req, res, next) {
  let { name, password } = req.body;
  userModel.find({ name: name }).then(result => {
    if (result.length) {
      res.send({
        code: 0,
        msg: '注册失败，用户名已存在！'
      })
      return;
    }
    var hash = bcrypt.hashSync(password, salt); //密码加密
    new userModel({
      name: name,
      password: hash
    }).save().then(result => {
      res.send({
        code: 666,
        msg: '注册成功！'
      })
    }).catch(err => {
      console.log(err);
      res.send({
        code: 0,
        msg: '注册失败'
      })
    })
  })
});

//图片上传
const multer  = require('multer')
const storage = multer.diskStorage({
  destination: function (req, file, cb) { //指定图片存放路径
    cb(null, 'public/uploads')
  },
  filename: function (req, file, cb) { //自定义文件名
    // console.log(file);
    let type = file.mimetype.split('/')[1]  //获取图片后缀
    let name = Math.random().toString(36).substring(2) + Date.now() //保证图片名称唯一性
    cb(null, `${name}.${type}`)
  }
})
const upload = multer({ storage: storage })

router.post('/upload',upload.single('avatar'),(req,res)=>{
  console.log(req.file);
  res.send({
    code:666,
    msg:'上传成功',
    data:{
      url:`/uploads/${req.file.filename}`
    }
  })
})

router.put('/',(req,res)=>{ //用户信息更新
  console.log(req.body);
  let {userid,newInfo} = req.body
  userModel.updateOne({_id:userid},newInfo).then(result=>{
    res.send({
      code:666,
      msg:'用户信息更新成功'
    })
  })
})

router.get('/del',(req,res)=>{
  userModel.remove({_id:req.query.id}).then(result=>{
      console.log('删除成功');
      res.send({
        code:110,
        msg:'注销成功'
      })
  }).catch(err=>{
      console.log(err);
  })
})

module.exports = router;
